<!-- FavoritesList.vue -->
<template>
  <div class="favorites-content">

     <div class="favorites-header">
      <h2>我的收藏</h2>
      <el-button
        :type="isPublic ? 'primary' : 'info'"
        @click="toggleFavoritesVisibility"
        class="visibility-toggle-btn"
      >
        <el-icon>
          <View v-if="isPublic" />
          <Lock v-else />
        </el-icon>
        {{ isPublic ? '公开收藏' : '私密收藏' }}
      </el-button>
    </div>
    <div v-loading="loading" class="favorites-list">
      <el-empty v-if="favorites.length === 0" description="暂无收藏" />
      <div v-else class="favorites-grid">
        <el-card v-for="post in favorites" :key="post.id" class="favorite-card">
          <!-- 帖子头部 -->
          <div class="favorite-header">
            <div class="user-info">
              <div class="user-meta">
                <span class="username">{{ post.user.username }}</span>
                <span class="post-time">
                  <el-icon><Clock /></el-icon>
                  {{ formatTime(post.created_at) }}
                </span>
              </div>
            </div>
            <el-tag
              :type="getTagType(post.topic)"
              effect="light"
              class="topic-tag"
            >
              {{ post.topic }}
            </el-tag>
          </div>

          <!-- 帖子内容预览 -->
          <div class="favorite-content" @click="openPostDetail(post)">
            <h3 class="content-title">{{ extractTitle(post.content) }}</h3>
            <p class="content-preview">{{ getPreviewContent(post.content) }}</p>
          </div>

          <!-- 帖子统计信息 -->
          <div class="favorite-stats">
            <div class="stats-item">
              <el-icon><ChatRound /></el-icon>
              <span>{{ postCommentsCount[post.id] || 0 }} 评论</span>
            </div>
            <div class="stats-item">
              <el-icon><Thumb /></el-icon>
              <span>{{ post.likes_count }} 赞</span>
            </div>
          </div>

          <!-- 帖子操作栏 -->
          <div class="favorite-actions">
            <el-button
              type="primary"
              link
              class="action-button"
              @click="openPostDetail(post)"
            >
              <el-icon><View /></el-icon>
              查看详情
            </el-button>
            <el-button
              type="danger"
              link
              class="action-button"
              @click.stop="handleUnfavorite(post)"
            >
              <el-icon><Star /></el-icon>
              取消收藏
            </el-button>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 帖子详情弹窗 -->
    <el-dialog
      v-model="showPostDetail"
      title="帖子详情"
      width="800px"
      :before-close="closePostDetail"
      class="post-detail-dialog"
    >
      <PostDetail
        v-if="currentPost"
        :post="currentPost"
        :current-user="userInfo"
        :is-teacher="userInfo.role === 'teacher'"
        @back="closePostDetail"
        @update:post="handlePostUpdate"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {Thumb, Star, Clock, ChatRound, View, User,Lock } from '@element-plus/icons-vue'
import PostDetail from "@/components/CourseDiscussion/PostDetail.vue"
import axios from 'axios'

const props = defineProps({
  userInfo: {
    type: Object,
    required: true
  }
})

// 是否公开
const isPublic = ref(false)
// 关注状态的响应式引用
const followingList = ref([])

const loading = ref(false)
const favorites = ref([])
const showPostDetail = ref(false)
const currentPost = ref(null)
const postCommentsCount = ref({}) // 存储每个帖子的评论数量



// 切换收藏夹可见性
const toggleFavoritesVisibility = async () => {
  try {
    const response = await axios.put(
      '/backend/api/account/favorites/toggle_visibility/',
      {},
      { withCredentials: true }
    )

    // 更新可见性状态
    isPublic.value = !isPublic.value

    // 显示成功消息
    ElMessage.success(
      isPublic.value
        ? '收藏夹已切换为公开'
        : '收藏夹已切换为私密'
    )
  } catch (error) {
    console.error('切换收藏夹可见性失败:', error)
    ElMessage.error('切换收藏夹可见性失败')
  }
}


// 获取关注数据的方法
const fetchFollowData = async () => {
  try {
    const response = await axios.get('/backend/api/account/follow_data/', {
      withCredentials: true
    })

    if (response.data && response.data.following) {
      followingList.value = response.data.following
      // 更新所有帖子的作者关注状态
      favorites.value = favorites.value.map(post => ({
        ...post,
        user: {
          ...post.user,
          is_followed: followingList.value.includes(post.user.id)
        }
      }))
    }
  } catch (error) {
    console.error('获取关注数据失败:', error)
  }
}


// 获取收藏列表
const fetchFavorites = async () => {
  loading.value = true
  try {
    const response = await axios.get(`/backend/api/post/users/${props.userInfo.id}/favorites/`, {
      withCredentials: true
    })

    // 先获取关注数据
    const followResponse = await axios.get('/backend/api/account/follow_data/', {
      withCredentials: true
    })

    if (followResponse.data && followResponse.data.following) {
      followingList.value = followResponse.data.following
    }

    // 更新帖子列表，包含关注状态
    favorites.value = response.data.map(post => ({
      ...post,
      user: {
        ...post.user,
        is_followed: followingList.value.includes(post.user.id)
      }
    }))

    // 获取每个帖子的评论数量
    await Promise.all(favorites.value.map(fetchPostCommentsCount))
  } catch (error) {
    console.error('获取收藏列表失败:', error)
    ElMessage.error('获取收藏列表失败')
  } finally {
    loading.value = false
  }
}

// 获取单个帖子的评论数量
const fetchPostCommentsCount = async (post) => {
  try {
    const response = await axios.get(`/backend/api/post/${post.id}/comments/`, {
      withCredentials: true
    })
    postCommentsCount.value[post.id] = response.data.length
  } catch (error) {
    console.error(`获取帖子 ${post.id} 评论数量失败:`, error)
    postCommentsCount.value[post.id] = 0
  }
}

// 取消收藏
const handleUnfavorite = async (post) => {
  try {
    await ElMessageBox.confirm('确定要取消收藏这篇帖子吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await axios.post(
      `/backend/api/post/${post.id}/unfavorite/`,
      {},
      { withCredentials: true }
    )

    if (response.data.message) {
      ElMessage.success('已取消收藏')
      await fetchFavorites() // 重新获取收藏列表和评论数量
    }
  } catch (error) {
    if (error === 'cancel') return
    console.error('取消收藏失败:', error)
    ElMessage.error('取消收藏失败')
  }
}

// 获取标签类型
const getTagType = (topic) => {
  const types = {
    '问题': 'danger',
    '分享': 'success',
    '讨论': 'warning',
    '建议': 'info'
  }
  return types[topic] || 'info'
}

// 打开帖子详情
const openPostDetail = async (post) => {
  try {
    const response = await axios.get(`/backend/api/post/${post.id}/`, {
      withCredentials: true
    })
    currentPost.value = response.data
    showPostDetail.value = true
  } catch (error) {
    console.error('获取帖子详情失败:', error)
    ElMessage.error('获取帖子详情失败')
  }
}

// 关闭帖子详情
const closePostDetail = () => {
  showPostDetail.value = false
  currentPost.value = null
}

// 处理帖子更新
const handlePostUpdate = async (updatedPost) => {
  const index = favorites.value.findIndex(p => p.id === updatedPost.id)
  if (index !== -1) {
    // 保持关注状态
    const isFollowed = followingList.value.includes(updatedPost.user.id)
    favorites.value[index] = {
      ...updatedPost,
      user: {
        ...updatedPost.user,
        is_followed: isFollowed
      }
    }
    // 更新评论数量
    await fetchPostCommentsCount(updatedPost)
  }
  currentPost.value = {
    ...updatedPost,
    user: {
      ...updatedPost.user,
      is_followed: followingList.value.includes(updatedPost.user.id)
    }
  }
}


// 提取标题
const extractTitle = (content) => {
  try {
    const parser = new DOMParser()
    const doc = parser.parseFromString(content, 'text/html')
    const titleElement = doc.querySelector('title')
    return titleElement ? titleElement.textContent : '无标题'
  } catch (e) {
    return '无标题'
  }
}

// 获取预览内容
const getPreviewContent = (content) => {
  try {
    const parser = new DOMParser()
    const doc = parser.parseFromString(content, 'text/html')
    const paragraphs = doc.querySelectorAll('p')
    let previewText = ''
    for (let i = 0; i < paragraphs.length && previewText.length < 200; i++) {
      previewText += paragraphs[i].textContent + ' '
    }
    return previewText.slice(0, 200) + (previewText.length > 200 ? '...' : '')
  } catch (e) {
    return '内容解析失败'
  }
}

// 格式化时间
const formatTime = (timeStr) => {
  const date = new Date(timeStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  fetchFavorites()
  fetchFollowData()
})
</script>

<style scoped>
/* 样式保持不变 */
.favorites-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
}

.favorites-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
  padding: 16px;
}

.favorite-card {
  border-radius: 12px;
  transition: all 0.3s ease;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.favorite-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.favorite-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-meta {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.username {
  font-weight: 600;
  color: #2c3e50;
  font-size: 14px;
}

.post-time {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #909399;
  font-size: 12px;
}

.topic-tag {
  font-size: 12px;
  padding: 0 8px;
  height: 24px;
  line-height: 24px;
}

.favorite-content {
  flex-grow: 1;
  cursor: pointer;
  padding: 16px 0;
}

.content-title {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.content-preview {
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin-bottom: 16px;
}

.favorite-stats {
  display: flex;
  gap: 16px;
  padding: 12px 0;
  border-top: 1px solid #f0f2f5;
}

.stats-item {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #909399;
  font-size: 13px;
}

.favorite-actions {
  display: flex;
  justify-content: space-between;
  padding-top: 12px;
  border-top: 1px solid #f0f2f5;
}

.action-button {
  display: flex;
  align-items: center;
  gap: 4px;
}

.post-detail-dialog :deep(.el-dialog__body) {
  padding: 0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .favorites-content {
    padding: 16px;
  }

  .favorites-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
}


.user-top {
  display: flex;
  align-items: center;
  gap: 8px;
}

.follow-btn {
  padding: 2px 8px;
  font-size: 12px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.follow-btn.is-following {
  color: #409EFF;
}

.follow-btn:hover:not(.is-following) {
  background-color: #f5f7fa;
}

.follow-btn.is-following:hover {
  color: #f56c6c;
}

.follow-btn.is-following:hover::after {
  content: '取消关注';
}

.follow-btn.is-following:hover .el-icon,
.follow-btn.is-following:hover span {
  display: none;
}


.favorites-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.visibility-toggle-btn {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style>